//
//  HJInformationTabController.m
//  KaiChat
//
//  Created by lx on 2024/3/11.
//

#import "HJInformationTabController.h"
#import "QMUIButton.h"
#import "HJInformationTabCell.h"
#import "HJInformationModel.h"
#import "HJInformationTabHeader.h"
#import "HJNewsTabListModel.h"
#import "HJInformationPresent.h"
#import "HJUserNewsTagModel.h"

@interface HJTabCustomFlowLayout : UICollectionViewFlowLayout
@end
  
@implementation HJTabCustomFlowLayout
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray<UICollectionViewLayoutAttributes *> *attributes = [super layoutAttributesForElementsInRect:rect];
    // 在这里可以调整或返回自定义的布局属性数组
//    return attributes;
    
    CGFloat originX = attributes.firstObject.frame.origin.x;
    CGFloat curX = 0;
    for (UICollectionViewLayoutAttributes *att in attributes) {
        if (att.representedElementCategory == UICollectionElementCategoryCell) {
            CGRect frame = att.frame;
            if (frame.origin.x == originX) {
                curX = originX;
            }
            frame.origin.x = curX;
            att.frame = frame;
            curX += 10 + frame.size.width;
        }
    };
    return attributes;
}
@end



@interface HJInformationTabController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) HJTabCustomFlowLayout *flowLayout;
@property (nonatomic, assign) BOOL isLikeChange;
@property (nonatomic, strong) NSArray *datas;

@end

@implementation HJInformationTabController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.clearColor;
    
    _isLikeChange = false;
    
    CGFloat contentViewH = TabbarSafeBottomMargin + KScreenHeight * 0.8;
    UIButton *maskView = [[UIButton alloc] initWithFrame:self.view.bounds].addTo(self.view);
    maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [maskView addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    _maskView = maskView;
    
    UIView *contentView = [UIView addToView:maskView];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, contentViewH);
    [contentView addRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:20];
    _contentView = contentView;
    
    QMUIButton *closeButton = [QMUIButton addToView:contentView];
    [closeButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:[UIImage imageNamed:@"nav_close"] forState:UIControlStateNormal];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(15);
        make.width.height.offset(30);
        make.left.offset(15);
    }];
    
    _flowLayout = [[HJTabCustomFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _flowLayout.minimumLineSpacing = 10;
    _flowLayout.minimumInteritemSpacing = 10;
    _flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    [_collectionView registerClass:[HJSelectTabCell class] forCellWithReuseIdentifier:@"HJSelectTabCell"];
    [_collectionView registerClass:HJInformationTabHeader.self forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HJInformationTabHeader"];
    _collectionView.collectionViewLayout = _flowLayout;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = UIColor.whiteColor;
    _collectionView.alwaysBounceVertical = YES;
    [contentView addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(45);
        make.bottom.inset(0);
    }];
    
    [self loadData];
}

#pragma data
- (void)loadData {
    [self showLoadingInView:self.contentView];
    [HJInformationPresent loadNewsTagsListWithTypeNewsTypeId:self.typeId complete:^(NSArray * _Nullable datas) {
        [self hiddenLoadingInView:self.contentView];
        self.datas = datas;
        [self.collectionView reloadData];
    }];
}

#pragma mark - action
- (void)didClickDismissButton {
    [self dismissComplete:nil];
}

#pragma mark - Source\delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.datas.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.datas[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HJSelectTabCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HJSelectTabCell" forIndexPath:indexPath];
    HJNewsTabModel *model = self.datas[indexPath.section][indexPath.row];
    model.isLike = indexPath.section == 0;
    cell.model = model;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    HJInformationTabHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HJInformationTabHeader" forIndexPath:indexPath];
    
    TJWeakify(self)
    [header setDidClickRightButtonBlock:^(UIImageView * _Nonnull refreshIconImageView) {
        [weakself didClickRightButtonWithRefreshIconImageView:refreshIconImageView];
    }];
    if (indexPath.section == 0) {
        header.titleLabel.text = @"Like";
        header.isShowRefresh = NO;
 
    } else {
        header.isShowRefresh = YES;
        header.titleLabel.text = @"Tag";
    }
    
    return header;
}

- (void)didClickRightButtonWithRefreshIconImageView:(UIImageView *)refreshIconImageView {
    
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = @(M_PI * 2); // 旋转360度
    rotationAnimation.duration = 2.0; // 动画持续时间
    rotationAnimation.repeatCount = HUGE_VALF; // 无限循环
    
    [refreshIconImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

    [HJInformationPresent loadNewsTagsListWithTypeNewsTypeId:self.typeId complete:^(NSArray * _Nullable datas) {
        self.datas = datas;
        [self.collectionView reloadData];
        [refreshIconImageView.layer removeAnimationForKey:@"rotationAnimation"];
    }];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(KScreenWidth, 50);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    HJNewsTabModel *model = self.datas[indexPath.section][indexPath.row];
    return model.textSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *tags = self.datas[indexPath.section];
    HJNewsTabModel *selectTabModel = tags[indexPath.row];
    
    [HJHUD showGraceTimeLoadingInView:self.view];
    
    [HJInformationPresent updateUserTagsWithTypeNewsTypeId:self.typeId tagId:selectTabModel.tagID isAdd:indexPath.section == 1 complete:^(NSError * _Nullable error) {
        
        if (error) return;
        
        
        if (indexPath.section == 1) {
            
            NSMutableArray *likeTags = self.datas[0];
            NSMutableArray *allTags = self.datas[1];
            
            [likeTags insertObject:selectTabModel atIndex:0];
            [allTags removeObject:selectTabModel];
            
        } else {
            
            NSMutableArray *likeTags = self.datas[0];
            NSMutableArray *allTags = self.datas[1];
            
            [allTags insertObject:selectTabModel atIndex:0];
            [likeTags removeObject:selectTabModel];
            
            NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"tagID" ascending:YES];
            [likeTags sortUsingDescriptors:@[sortDescriptor]];
        }
        
        [self.collectionView reloadData];
        
        if (self.likeTagDidChangeBlock) {
            self.likeTagDidChangeBlock(self.datas.firstObject, indexPath.section == 1, selectTabModel);
            
            HJUserNewsTagModel *model = [[HJUserNewsTagModel alloc] init];
            model.typeId = toString(@(self.typeId));
            model.userId = HJUserInfo.userId;
            model.userTags = self.datas.firstObject;
            model.allTags = self.datas.lastObject;
            [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {}];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.tj_y = KScreenHeight - self.contentView.tj_height;
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    } completion:^(BOOL finished) {
    }];
    
}

- (void)dismissComplete:(void (^)(void))complete {
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self.contentView.tj_y = KScreenHeight;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (complete) {
                complete();
            }
        }];
    }];
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}

- (void)dealloc {
    TJLog(@"%s", __func__);
}

@end



